package cn.zzzly.servlet;

import cn.zzzly.itest.Test;
import cn.zzzly.sql.Sql;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
 * @author Zzzyl
 * @date 2020-10-27
 */

public class YiqingServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        req.setCharacterEncoding("utf-8");
        //获取username、password、qq、留言、时间
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String qq = req.getParameter("qq");
        String message = req.getParameter("message");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        String time = formatter.format(date);
        //创建模拟登录对象
        Test test = new Test();
        String yz = test.yz(username, password);
        resp.setContentType("text/html; charset=UTF-8"); //转码
        PrintWriter out = resp.getWriter();
        ((PrintWriter) out).flush();
        //账号不完整
        if (qq.equals("") || username.equals("") || password.equals("")) {
            out.println("<script>alert(\"请填写完整信息后提交\");history.back()</script>");

        }
        //账号验证通过
        else if (yz.equals("success")) {
            //创建sql对象
            Sql sql = new Sql();
            boolean select = true;
            try {
                select = sql.select(username);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            //数据库无账号，开始插入
            if (!select) {
                boolean insert = sql.insert(username, password, qq, message, time);
                int rowCount = sql.rowCount();
                if (insert) {
                    out.println("<script>alert(\"提交成功！你是第"+rowCount+"位使用者\");history.back()</script>");

                } else {
                    out.println("<script>alert(\"提交失败，请联系开发者\");history.back()</script>");

                }
            }
            //数据库有账号
            else  {
                out.println("<script>alert(\"账号已提交过，请不要重复提交\");history.back()</script>");

            }
        //账号秘密错误
        } else {
            out.println("<script>alert(\"账号或密码错误，请检查\");history.back()</script>");
        }
    }
    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
